﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;

namespace Workers
{
    public class Splitter : Worker
    {
        private string m_fileToSplit;

        private string m_destinationPath;

        private int m_splitSize;

        public void Run(string fileToSplit, string destinationPath, int splitSize)
        {
            m_fileToSplit = fileToSplit;
            m_destinationPath = destinationPath;
            m_splitSize = splitSize;

            m_backgroundWorker.DoWork += new DoWorkEventHandler(Splitter_DoWork);
            m_backgroundWorker.RunWorkerAsync();
        }

        private void Splitter_DoWork(object sender, DoWorkEventArgs e)
        {
            int steps = (int)(new FileInfo(m_fileToSplit).Length / m_splitSize);

            FileStream fs = new FileStream(m_fileToSplit, FileMode.Open, FileAccess.Read);
            using (BinaryReader br = new BinaryReader(fs))
            {
                int counter = 1;
                bool isReadingComplete = false;
                while (!isReadingComplete)
                {
                    if ((sender as BackgroundWorker).CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    byte[] input = br.ReadBytes(m_splitSize);
                    using (FileStream writeFs = new FileStream(m_destinationPath +
                        Path.DirectorySeparatorChar + Path.GetFileName(m_fileToSplit) + "." + counter,
                        FileMode.Create))
                    {
                        using (BinaryWriter bw = new BinaryWriter(writeFs))
                        {
                            bw.Write(input);
                        }
                    }

                    isReadingComplete = (input.Length != m_splitSize);
                    if (!isReadingComplete)
                    {
                        (sender as BackgroundWorker).ReportProgress((int)(((float)counter / (float)steps) * 100));
                        counter += 1;
                    }
                }
            }
        }
    }
}
